﻿using Autofac;
using System.Reflection;
using Module = Autofac.Module;

namespace Inventory.API
{
    public class AutofaModuleRegister : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // 加载名为"test.Infrastructure"的程序集
            var applicationAssembly = Assembly.Load("Inventory.Infrastructure");

            // 遍历程序集中的所有类型
            foreach (var temp in applicationAssembly.GetTypes())
            {
                Console.WriteLine("Type: " + temp.Name);
            }

            // 获取所有具体实现类和其接口
            var types = applicationAssembly.GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericType) // 只选择具体类且不是泛型
                .SelectMany(t => t.GetInterfaces(), (t, i) => new { Implementation = t, Interface = i })
                .Where(x => !x.Interface.IsGenericType || x.Interface.IsGenericTypeDefinition == false) // 过滤掉开放泛型接口
                .Where(x => !x.Interface.Name.Contains("Base")) // 过滤掉基类
                .Where(x => x.Interface.Name.EndsWith("Repository"))
                .ToList();

            // 注册所有接口和实现
            foreach (var type in types)
            {
                Console.WriteLine("Interface: " + type.Interface.Name + " Implementation: " + type.Implementation.Name);
                builder.RegisterType(type.Implementation).As(type.Interface);
            }
        }

    }
}
